var t = require("../../../@babel/runtime/helpers/interopRequireDefault")
    .default,
  e = t(require("../../../utils/qqmap")),
  s = require("../../../utils/http"),
  n = t(require("../../../utils/util"));
 new s.HTTP();
 
let { addzcGj,theonefollow,
  hgjfilesfollow, } = require("../../../api/attract/qd_content");
Page({
  data: {
    now_time: "",
    current_address: "",
    status: 0,
    now_time_stop: "",
    imgUrl: "",
    fileList: [],
    sortType: "",
  },
  onLoad: function (t) {
    const query = wx.createSelectorQuery();
    console.log(query.select("#mycanvas"));

    this.setData({
      sortType: t.sortType,
    });
    this.getCurrentTime(),
      this.getLocation(),
      this.setData({
        now_time: this.getTime(),
      }),
      this.getParams();
  },
  getParams: function () {
    var t = this;
    wx.request({
      url: "https://www.qlsyyun.com:3030/getParams",
      success: function (e) {
        console.log(e.data);
        t.setData({
          ossSignature: e.data.signature,
          ossAccessKeyId: e.data.OSSAccessKeyId,
          ossPolicy: e.data.policy,
        });
      },
      fail: function (t) {
        console.log("请求签名失败：", t);
      },
    });
  },

  drawText: function (
    ctx,
    str,
    leftWidth,
    initHeight,
    titleHeight,
    canvasWidth
  ) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) {
        //绘制剩余部分
        ctx.fillText(
          str.substring(lastSubStrIndex, i + 1),
          leftWidth,
          initHeight
        );
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight;
  },

  // 删除图片
  deleteImage(e) {
    let { file } = e.detail;
    this.setData({
      fileList: this.data.fileList.filter((item) => item.url !== file.url),
    });
  },
  // 上传图片
  afterRead(event) {
    let t = this;
    var n = new Date(),
      a =
        "photo/" +
        n.getFullYear() +
        "-" +
        (n.getMonth() + 1) +
        "/" +
        Date.parse(new Date()) +
        parseInt(90001 * Math.random() + 1e4, 10) +
        ".jpeg";
    wx.uploadFile({
      url: "https://qlsy.oss-cn-hangzhou.aliyuncs.com",
      // filePath: t.data.fileList[0].url,
      filePath: event.detail.file.url,
      name: "file",
      formData: {
        key: a,
        policy: t.data.ossPolicy,
        OSSAccessKeyId: t.data.ossAccessKeyId,
        signature: t.data.ossSignature,
      },
      success(res) {
        // 上传完成需要更新 fileList
        console.log("https://qlsy.oss-cn-hangzhou.aliyuncs.com/" + a);
        let list = [];
        list.push({
          url: "https://qlsy.oss-cn-hangzhou.aliyuncs.com/" + a,
        });
        t.setData({
          fileList: list,
        });
      },
      fail(err) {
        console.log(err);
      },
    });
  },

  beforeRead(event) {
    const { file } = event.detail;
    let t = this;
    let date = new Date();
    let year = date.getFullYear();
    let month = ("0" + (date.getMonth() + 1)).slice(-2);
    let day = ("0" + date.getDate()).slice(-2);
    let hours = ("0" + date.getHours()).slice(-2);
    let minutes = ("0" + date.getMinutes()).slice(-2);
    let seconds = ("0" + date.getSeconds()).slice(-2);
    let currentTime =
      year +
      "-" +
      month +
      "-" +
      day +
      " " +
      hours +
      ":" +
      minutes +
      ":" +
      seconds;
    const currentLocation = t.data.current_address;
    const files = [];
    files.push(event.detail.file);
    files.forEach((file, index) => {
      wx.getImageInfo({
        src: file.url,
        success(res) {
          file.width = res.width;
          file.height = res.height;
          t.setData({
            canvasWidthValue: res.width,
            canvasHeightValue: res.height,
          });
          file.url = res.path;
          file.currentTime = currentTime;
          file.currentLocation = currentLocation;
          const query = wx.createSelectorQuery();
          query
            .select("#mycanvas")
            .fields({
              node: true,
              size: true,
            })
            .exec((res) => {
              const canvas = res[0].node;
              const ctx = canvas.getContext("2d");
              const img = canvas.createImage();
              img.src = file.url;
              img.onload = () => {
                //设置画布到校绘制原图到canvas中
                ctx.canvas.width = file.width / 2;
                ctx.canvas.height = file.height / 2;
                ctx.drawImage(img, 0, 0, file.width / 2, file.height / 2);
                // 设置水印字体大小、颜色和位置
                ctx.font = "20px arial";
                ctx.fillStyle = "red";
                ctx.textAlign = "left";
                ctx.textBaseline = "bottom";
                // 绘制时间和位置信息到canvas中
                ctx.fillText(currentTime, 10, 60);

                t.drawText(
                  ctx,
                  currentLocation,
                  10,
                  90,
                  232,
                  (t.data.windowWidth / 6) * 5
                ); // 自动换行
                setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvas,
                    success(res) {
                      file.url = res.tempFilePath;
                      let list = [];
                      list.push({
                        url: res.tempFilePath,
                        // deletable: true,
                      });
                      t.setData({
                        fileList: list,
                        flag: true,
                      });
                    },
                    fail(res) {
                      console.error("失败", res);
                    },
                  });
                });
              };
            });
        },
      });
    });
  },

  selectFile: function () {
    var t = this;
    let sourceType = [];
    if (t.data.sortType == 1) {
      sourceType = ["camera"];
    } else {
      sourceType = ["album", "camera"];
    }

    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: sourceType,
      success: function (e) {
        let date = new Date();
        let year = date.getFullYear();
        let month = ("0" + (date.getMonth() + 1)).slice(-2);
        let day = ("0" + date.getDate()).slice(-2);
        let hours = ("0" + date.getHours()).slice(-2);
        let minutes = ("0" + date.getMinutes()).slice(-2);
        let seconds = ("0" + date.getSeconds()).slice(-2);
        let currentTime =
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          minutes +
          ":" +
          seconds;
        const currentLocation = t.data.current_address;
        e.tempFiles.forEach((file, index) => {
          console.log(file);
          wx.getImageInfo({
            src: file.tempFilePath,
            success(res) {
              file.width = res.width;
              file.height = res.height;
              t.setData({
                canvasWidthValue: res.width,
                canvasHeightValue: res.height,
              });
              file.tempFilePath = res.path;
              file.currentTime = currentTime;
              file.currentLocation = currentLocation;
              const query = wx.createSelectorQuery();
              console.log(query.select("#mycanvas"));
              query
                .select("#mycanvas")
                .fields({
                  node: true,
                  size: true,
                })
                .exec((res) => {
                  const canvas = res[0].node;
                  const ctx = canvas.getContext("2d");
                  const img = canvas.createImage();
                  img.src = file.tempFilePath;
                  img.onload = () => {
                    //设置画布到校绘制原图到canvas中
                    ctx.canvas.width = file.width / 2;
                    ctx.canvas.height = file.height / 2;
                    ctx.drawImage(img, 0, 0, file.width / 2, file.height / 2);
                    // 设置水印字体大小、颜色和位置
                    ctx.font = "20px arial";
                    ctx.fillStyle = "red";
                    ctx.textAlign = "left";
                    ctx.textBaseline = "bottom";
                    // 绘制时间和位置信息到canvas中
                    ctx.fillText(currentTime, 10, 60);

                    t.drawText(
                      ctx,
                      currentLocation,
                      10,
                      90,
                      232,
                      (t.data.windowWidth / 6) * 5
                    ); // 自动换行
                    setTimeout(() => {
                      wx.canvasToTempFilePath({
                        canvas,
                        success(res) {
                          file.tempFilePath = res.tempFilePath;
                          let list = [];
                          list.push({
                            url: res.tempFilePath,
                          });
                          t.setData({
                            fileList: list,
                            flag: true,
                          });
                          var s = res.tempFilePath;
                          if (s[0].size > 10485760)
                            wx.showToast({
                              title: "文件大小不能超过10M",
                              icon: "none",
                              duration: 3e3,
                            });
                          else {
                            var n = new Date(),
                              a =
                                "photo/" +
                                n.getFullYear() +
                                "-" +
                                (n.getMonth() + 1) +
                                "/" +
                                Date.parse(new Date()) +
                                parseInt(90001 * Math.random() + 1e4, 10) +
                                ".jpeg";
                            t.setData({
                              key: a,
                              imgUrl: s,
                            });
                          }
                        },
                        fail(res) {
                          console.error("失败", res);
                        },
                      });
                    }, 1000);
                  };
                });
            },
          });
        });
      },
    });
  },
  upload: function (t, e) {
    wx.showLoading({
      title: "上传中...",
      icon: "loading",
      mask: !0,
    }),
      wx.uploadFile({
        url: "https://qlsy.oss-cn-hangzhou.aliyuncs.com",
        filePath: e,
        name: "file",
        formData: {
          key: t,
          policy: this.data.ossPolicy,
          OSSAccessKeyId: this.data.ossAccessKeyId,
          signature: this.data.ossSignature,
        },
        success: function (e) {
          console.log(e);
          204 === e.statusCode &&
            (wx.setStorageSync(
              "addressgj",
              "https://qlsy.oss-cn-hangzhou.aliyuncs.com/" + t
            ),
            wx.showToast({
              title: "提交成功",
              icon: "none",
              duration: 1e3,
              mask: !0,
              success: function () {
                let time = new Date().getTime();
                //将时间戳格式转换成年月日时分秒
                let date = new Date(time);
                let bbTime = `${date.getFullYear()}-${
                  date.getMonth() + 1 < 10
                    ? "0" + (date.getMonth() + 1)
                    : date.getMonth() + 1
                }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()}`;
                let tjTime = `${
                  date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
                }:${date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()}:${
                  date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()}`;
                let infor = wx.getStorageSync("infor");
                let user = wx.getStorageSync("userInfoMy");
                let location = wx.getStorageSync("nowaddress");
                let image = wx.getStorageSync("addressgj");
                  let isFollow = true
                  // 判断当前客户当天是否跟进
                  new s.HTTP().request({
                    url: "https://www.qlsyyun.com:3000/isFollow/today",
                    method: 'POST',
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded"
                    },
                    data: {
                      qymc: infor.qymc,
                      tjsj: `${bbTime} ${tjTime}`
                    },
                  }).then(res => {
                    if (res.length > 0) {
                      isFollow = false
                      wx.showToast({
                        title: '当天已跟进该客户',
                        icon: "none",
                        duration: 1e3
                      })
                    }
                    if (isFollow === false) return 
                    console.log(isFollow)
                  }).then(()=>{
                    addzcGj({
                      qymc: infor.qymc,
                      zsy: user.jname,
                      bm: user.bm,
                      bid: infor.bID,
                      khbh: infor.khbh,
                    }).then((res) => {
                      theonefollow({
                        qymc: infor.qymc,
                        bm: user.bm,
                        zsy:user.jname,
                        jdsm: `添加了渠道${infor.qymc}的跟进记录`,
                        dksj: `${bbTime} ${tjTime}`,
                        scsj: `${bbTime}`,
                        image: image,
                        address: location,
                        khbh: infor.khbh,
                        gjid: res.data[0].ID,
                      }).then(() => {
                        hgjfilesfollow({
                          mc: image,
                          hid: infor.bID,
                          FileUrl: image,
                          AddTime: `${bbTime} ${tjTime}`,
                          gid:  res.data[0].ID,
                          khbh: infor.khbh,
                          tname:user.jname,
                        }).then(() => {
                          wx.showToast({
                            title: "跟进记录添加完成",
                          });
                          wx.removeStorageSync("nowaddress");
                          wx.removeStorageSync("addressgj");
                        });
                      });
                    });
                    setTimeout(function () {
                      var pages = getCurrentPages();
                      var beforePage = pages[pages.length - 2];
                      // 假设main()为页面A的数据方法，
                      beforePage.onLoad({
                        qdid: infor.bID,
                        id: 1
                      });
                      wx.navigateBack({
                        delta: 1,
                      });
                    }, 1e3);

                  })
        

               
              },
            }));
        },
        fail: function (t) {
          wx.showLoading({
            title: "上传失败，请稍后重试",
            icon: "loading",
            mask: !0,
          });
        },
        complete: function () {
          wx.hideLoading();
        },
      });
  },
  clockInStart: function () {
    return this.data.imgUrl
      ? this.data.current_address
        ? (wx.vibrateLong(),
          this.setData(
            {
              status: 1,
              now_time_stop: this.data.now_time,
              clockTime: n.default.formatDate(new Date()),
            },
            wx.showToast({
              title: "打卡成功",
              icon: "none",
            })
          ),
          wx.setStorageSync("clocks", this.data.now_time),
          wx.setStorageSync("clockTime", this.data.clockTime),
          wx.setStorageSync("nowaddress", this.data.current_address),
          void this.upload(this.data.key, this.data.imgUrl))
        : wx.showToast({
            title: "未获取当前定位",
            icon: "error",
          })
      : wx.showToast({
          title: "尚未上传打卡照",
          icon: "error",
        });
  },
  getCurrentTime: function () {
    var t = this;
    setInterval(function () {
      t.setData({
        now_time: t.getTime(),
      });
    }, 1e3);
  },
  getTime: function () {
    return (
      new Date().getHours() +
      ":" +
      (new Date().getMinutes() < 10
        ? "0" + new Date().getMinutes()
        : new Date().getMinutes()) +
      ":" +
      (new Date().getSeconds() < 10
        ? "0" + new Date().getSeconds()
        : new Date().getSeconds())
    );
  },
  getUserAuth: function () {
    var t = this;
    return new Promise(function (e, s) {
      wx.authorize({
        scope: "scope.userLocation",
      })
        .then(function () {
          e();
        })
        .catch(function () {
          var e = t;
          wx.getSetting({
            success: function (t) {
              null != t.authSetting["scope.userLocation"] &&
              1 != t.authSetting["scope.userLocation"]
                ? wx.showModal({
                    title: "请求授权当前位置",
                    content: "需要获取您的地理位置，请确认授权",
                    success: function (t) {
                      t.cancel
                        ? wx.showToast({
                            title: "拒绝授权",
                            icon: "none",
                            duration: 1e3,
                          })
                        : t.confirm &&
                          wx.openSetting({
                            success: function (t) {
                              1 == t.authSetting["scope.userLocation"]
                                ? e.getLocation()
                                : wx.showToast({
                                    title: "授权失败",
                                    icon: "none",
                                    duration: 1e3,
                                  });
                            },
                          });
                    },
                  })
                : (t.authSetting["scope.userLocation"], e.getLocation());
            },
          });
        });
    });
  },
  getLocation: function () {
    console.log(e);
    var t = this;
    wx.getLocation({
      type: "gcj02",
      success: function (s) {
        console.log(s);
        var n = s.longitude,
          a = s.latitude,
          o = a + "," + n;
        t.translate(o).then(function (t) {
          t.locations && ((a = t.locations[0].lat), (n = t.locations[0].lng));
        }),
          e.default.reverseGeocoder({
            location: {
              latitude: a,
              longitude: n,
            },
            success: function (e) {
              var s = e.result.address + e.result.formatted_addresses.recommend;
              t.setData({
                current_address: s,
              });
              console.log(t.data.current_address);
            },
            fail: function (t) {
              console.log(t);
            },
          });
      },
      fail: function (e) {
        t.getUserAuth(),
          wx.showToast({
            title: "获取定位失败，请打开手机定位，重新进入！",
            icon: "none",
          });
      },
    });
  },
  refreshAdd: function () {
    this.getLocation();
  },
  translate: function (t) {
    return new Promise(function (e, s) {
      wx.request({
        url: "https://apis.map.qq.com/ws/coord/v1/translate",
        method: "GET",
        data: {
          locations: t,
          type: 5,
          key: "CREBZ-B7PKX-GL44O-7ITDB-7UFU7-OLFDV",
        },
        success: function (t) {
          return e(t.data);
        },
        fail: function (t) {
          return s(t);
        },
      });
    });
  },
  deleteImg: function (t) {
    this.setData({
      imgUrl: "",
    });
  },
  previewImg: function (t) {
    wx.previewImage({
      current: this.data.imgUrl,
      urls: [this.data.imgUrl],
    });
  },
});
